class Ems::StoreStaffEventsController < Ems::BaseController
  before_action :set_staff, except: [:index]
  def index
    set_search_params
    set_month

    @q = current_store.store_staffs.available.includes(:events, :store_department, :store_position).ransack(params[:q])
    @store_staffs = @q.result.order("id asc")
  end

  def new
    @event = StoreStaffEvent.new()
  end

  def create
    @event = @staff.events.new(stoe_staff_event_params)
    if @event.save
      redirect_to ems_store_staff_events_path
    else
      redirect_to new_ems_store_staff_event_path(store_staff_id: @staff.id)
    end
  end

  private
  def set_staff
    @staff = StoreStaff.find(params[:store_staff_id])
  end

  def stoe_staff_event_params
    params[:store_staff_event][:store_id] = current_store.id
    params.require(:store_staff_event).permit(
      :started_at,
      :ended_at,
      :type,
      :sort,
      :hour,
      :remark,
      :creator_id,
      :amount,
      :store_id,
      :occur_on
    )
  end

  def set_search_params
    params[:q] ||= {}
    @name = params[:q][:full_name_cont]
  end

  def set_month
    if params[:month].present?
      date_array = params[:month].split("-").map(&:to_i)
      @current_month = DateTime.new(date_array.first, date_array.last)
    else
      @current_month = Time.now
    end
    @format_month = @current_month.strftime("%Y-%m")
  end
end
